//  Copyright (c) 2008  Yoong-ki Ahn & Youngjin Kim < mexif@googlegroups.com>
//  See the enclosed file COPYING for license information (MIT Licence).
//  If you did not receive this file,
//  see http://www.opensource.org/licenses/mit-license.php.

#define _CRT_SECURE_NO_WARNINGS

#include "findfile.h"


FindFile::FindFile()
{
	hFile = 0;
}

FindFile::FindFile( const wchar_t * filter )
{
	hFile = 0;
	Init( filter );
}

FindFile::~FindFile()
{
	Close();
}

void FindFile::Init( const wchar_t * filter )
{
	Close();

	hFile = _wfindfirst64( filter, &c_file );
}

void FindFile::Close()
{
	if ( hFile )
	{
		_findclose( hFile );
		hFile = 0;
	}
}

void FindFile::Next()
{
	if ( hFile )
	{
		if ( _wfindnext64( hFile, &c_file ) )
			Close();
	}
}

bool FindFile::IsValid()
{
	return hFile != 0;
}


wstring_list LookupDirectory( const wchar_t * path )
{
	wstring_list targets;
	wstring_list dirs;

	wchar_t drive[4];
	wchar_t dir[_MAX_PATH];
	wchar_t filename[_MAX_PATH];
	wchar_t ext[_MAX_PATH];
	wchar_t mkpath[_MAX_PATH*2];

	_wsplitpath( path, drive, dir, filename, ext );
	dirs.push_back( path );

	while( !dirs.empty() )
	{
		_wsplitpath( dirs.front().c_str(), drive, dir, 0, 0 );
		dirs.pop_front();

		_wmakepath( mkpath, drive, dir, filename, ext );

		FindFile ff( mkpath );
		for ( ; ff.IsValid(); ff.Next() )
		{
			if ( ff.c_file.name[0] == '.' )
				continue;

			/// no need to dig inside source versioning system.
			if ( _wcsicmp( ff.c_file.name, L".svn" ) == 0 )
				continue;
			if ( _wcsicmp( ff.c_file.name, L".CVS" ) == 0 )
				continue;
			if ( _wcsicmp( ff.c_file.name, L"CVS" ) == 0 )
				continue;


			_wmakepath( mkpath, drive, dir, ff.c_file.name, 0 );

			if ( ff.c_file.attrib & _A_SUBDIR  )
			{
				wcscat( mkpath, L"\\" );
				wcscat( mkpath, filename );
				dirs.push_back( mkpath );
			}
			else
				targets.push_back( mkpath );
		}
	}


	return targets;
}

